package io.admin.common.utils;


import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WordMerger {
    private final  static String ADDRESS_FILE =ExcelUtils.ADDRESS_FILE;
    public static void mergeWordDocuments(String outputFile, String... inputFiles) throws IOException, InvalidFormatException {
        XWPFDocument destDocument = new XWPFDocument();

        for (String inputFile : inputFiles) {
            FileInputStream fis = new FileInputStream(ADDRESS_FILE+inputFile);
            XWPFDocument srcDocument = new XWPFDocument(fis);
            for (IBodyElement element : srcDocument.getBodyElements()) {
                // 只处理段落和表格
                if (element instanceof XWPFParagraph) {
                    XWPFParagraph paragraph = (XWPFParagraph) element;
                    destDocument.createParagraph();
                    appendParagraph(paragraph, destDocument.getLastParagraph());
                } else if (element instanceof XWPFTable) {
                    XWPFTable table = (XWPFTable) element;
                    destDocument.createTable();
                    appendTable(table, destDocument.getTables().get(destDocument.getTables().size() - 1));
                }
            }
            srcDocument.close();
            fis.close();
        }
        FileOutputStream fos = new FileOutputStream(outputFile);
        destDocument.write(fos);
        destDocument.close();
        fos.close();
    }

    private static void appendParagraph(XWPFParagraph srcPara, XWPFParagraph destPara) {
        for (XWPFRun run : srcPara.getRuns()) {
            destPara.createRun().setText(run.getText(0));
        }
    }

    private static void appendTable(XWPFTable srcTable, XWPFTable destTable) {
        for (int row = 0; row < srcTable.getNumberOfRows(); row++) {
            XWPFTableRow destRow = destTable.createRow();
            XWPFTableRow srcRow = srcTable.getRow(row);
            for (int col = 0; col < srcRow.getTableCells().size(); col++) {
                XWPFTableCell destCell = destRow.getCell(col);
                XWPFTableCell srcCell = srcRow.getTableCells().get(col);
                for (XWPFParagraph p : srcCell.getParagraphs()) {
                    destCell.addParagraph();
                    appendParagraph(p, destCell.getParagraphs().get(0));
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        String outputFile = "merged.docx";
        String[] inputFiles = { "12.docx", "11.docx"};
        mergeWordDocuments(outputFile, inputFiles);
    }
}
